#import "LayerMain.h"
#import "LayerSetPos.h"
#import "OpenFeint/OFHighScoreService.h"
#import "SimpleAudioEngine.h"
#import "TapBurstAppDelegate.h"

@implementation SceneMain
-(id)initWithMode:(int)mode time:(int)time {
	if ((self = [super init])) {
		LayerMain* l = [[[LayerMain alloc] initWithMode:mode time:time] autorelease];
		[self addChild:l z:0 tag:kLayerMain];
	}
	return self;
}

-(void)dealloc {
	[super dealloc];
}
@end


@implementation LayerMain

@synthesize mStartTime;

-(id) initWithMode:(int)mode time:(int)time {
	if( (self=[super init] )) {
		[self setIsTouchEnabled:YES];
		if (time == 0) mTime = 10;
		else if(time == 1) mTime = 20;
		else if(time == 2) mTime = 30;
		else if(time == 3) mTime = 60;
		mMode = mode;

		CGSize size = [[CCDirector sharedDirector] winSize];
		int w = size.width / 2;
		int h = size.height / 2;
		
		// BackGround
		CCSprite* bg = [CCSprite spriteWithFile:[NSString stringWithFormat:@"Bg%d.png",arc4random()%6+1]];
		[bg setPosition:ccp(w,h)];
		[self addChild:bg];

		// TimeBar
		CCSprite* timeLabel = [CCSprite spriteWithFile:@"Time.png"];
		[timeLabel setPosition:ccp(50, 450)];
		[self addChild:timeLabel];
		CCSprite* timeBarBg = [CCSprite spriteWithFile:@"TimeBarBG.png"];
		[timeBarBg setPosition:ccp(200, 450)];
		[self addChild:timeBarBg];
		mTimeBar = [CCSprite spriteWithFile:@"TimeBar.png"];
		[mTimeBar setAnchorPoint:ccp(0, 0.5)];
		[mTimeBar setPosition:ccp(100, 450)];
		[self addChild:mTimeBar];
		
		mTimeValue = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%.02f",mTime]
										fontName:@"CourierNewPS-BoldMT" fontSize:20];
		[mTimeValue setPosition:ccp(200, 448)];
		[self addChild:mTimeValue z:2];

		// Circle
		mCircle1 = [CCSprite spriteWithFile:@"TapBtn.png"];
		[self addChild:mCircle1];
		if(mMode == 0)
			[mCircle1 setPosition:ccp(w,kCircleY)];
		else {
			[mCircle1 setPosition:ccp(80,kCircleY)];
			mCircle2 = [CCSprite spriteWithFile:@"TapBtn.png"];
			[mCircle2 setPosition:ccp(240,kCircleY)];
			[self addChild:mCircle2];
		}

		// Score
		mScoreTotal = [CCLabelTTF labelWithString:@"0" fontName:@"DBLCDTempBlack" fontSize:72];
		[mScoreTotal setPosition:ccp(w, 380)];
		[self addChild:mScoreTotal];
		
		if(mMode == 1) {
			mScore1 = [CCLabelTTF labelWithString:@"0" fontName:@"DBLCDTempBlack" fontSize:36];
			[mScore1 setPosition:ccp(50, 400)];
			[self addChild:mScore1];
			mScore2 = [CCLabelTTF labelWithString:@"0" fontName:@"DBLCDTempBlack" fontSize:36];
			[mScore2 setPosition:ccp(270, 400)];
			[self addChild:mScore2];
		}
		
		// Tips
		mTips = [CCSprite spriteWithFile:@"Touch.png"];
		[mTips setPosition:ccp(w, 280)];
		[self addChild:mTips];
		
		// Menu
		mRetry = [CCMenuItemImage itemFromNormalImage:@"Retry.png"
														selectedImage:@"RetrySel.png"
															   target:self
															 selector:@selector(retry)];
		[mRetry setPosition:ccp(240,30)];
		mBack = [CCMenuItemImage itemFromNormalImage:@"Back.png"
													   selectedImage:@"BackSel.png"
															  target:self
															selector:@selector(back)];
		[mBack setPosition:ccp(80,30)];
		mMenu = [CCMenu menuWithItems:mRetry,mBack,nil];
		[mMenu setPosition:CGPointZero];
		[self addChild:mMenu];
		
		// Finish
		mFinish = [CCSprite spriteWithFile:@"Finish.png"];
		[self addChild:mFinish];
		
		[self reStart];
	}
	return self;
}

-(void)reStart {
	[self unschedule:@selector(drainTime)];	
	[mTimeBar setTextureRect:CGRectMake(0, 0, 200, 25)];
	[mTimeBar setColor:ccc3(0, 255, 0)];

	[mTimeValue setString:[NSString stringWithFormat:@"%.02f",mTime]];
	[mScoreTotal setString:@"0"];
	[mCircle1 setVisible:YES];
	if(mMode == 1) {
		[mCircle2 setVisible:YES];
		[mScore1 setString:@"0"];
		[mScore2 setString:@"0"];
	}
	[mTips setPosition:ccp(160,280)];
	[mTips setOpacity:255];
	mTouchState1 = mTouchState2 = kStateUngrabbed;
	mTouchCount1 = mTouchCount2 = 0;
	mGameState = kStateNone;
	[mRetry setVisible:NO];
	[mFinish setPosition:ccp(160,300)];
	[mFinish setOpacity:0];
}

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	switch(mGameState) {
		case kStateNone: {
			int count = [[touches allObjects] count];
			int i;
			BOOL start = NO;
			for (i =0; i < count; i++) {
				UITouch* touch = [[touches allObjects] objectAtIndex:i];
				int touchIn = [self containsTouchLocation:touch];
				if(touchIn >= 2 ) continue;
				else if(touchIn == 0) {
					start = YES;
					if(mTouchState1 == kStateGrabbed) continue;
					mTouchState1 = kStateGrabbed;
					mTouch1 = touch;
					mTouchCount1 ++;
					[mCircle1 runAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.01 scale:0.8],
										 [CCScaleTo actionWithDuration:0.01 scale:1.0],nil]];
					[mScore1 setString:[NSString stringWithFormat:@"%d",mTouchCount1]];
					[mScoreTotal setString:[NSString stringWithFormat:@"%d",mTouchCount1 + mTouchCount2]];
				}
				else if(touchIn == 1) {
					start = YES;
					if(mTouchState2 == kStateGrabbed) continue;
					mTouchState2 = kStateGrabbed;
					mTouch2 = touch;
					mTouchCount2 ++;
					[mCircle2 runAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.01 scale:0.8],
										 [CCScaleTo actionWithDuration:0.01 scale:1.0],nil]];
					[mScore2 setString:[NSString stringWithFormat:@"%d",mTouchCount2]];
					[mScoreTotal setString:[NSString stringWithFormat:@"%d",mTouchCount1 + mTouchCount2]];
				}
			}

			if(start) {
				[[SimpleAudioEngine sharedEngine] playEffect:@"Tap.wav"];
				mGameState = kStateBegin;
				self.mStartTime = [NSDate date];
				[self schedule:@selector(drainTime) interval:0.01];
				[mTips runAction:[CCSpawn actions:[CCFadeOut actionWithDuration:0.3],
								   [CCMoveBy actionWithDuration:0.3 position:ccp(0,50)],nil]];
			}
			break;
		}
		case kStateBegin:
		{
			int count = [[touches allObjects] count];
			int i;
			BOOL isTouch = NO;
			for (i =0; i < count; i++) {
				UITouch* touch = [[touches allObjects] objectAtIndex:i];
				int touchIn = [self containsTouchLocation:touch];
				if(touchIn >= 2 ) continue;
				else if(touchIn == 0) {
					isTouch = YES;
					if(mTouchState1 == kStateGrabbed) continue;
					mTouchState1 = kStateGrabbed;
					mTouch1 = touch;
					mTouchCount1 ++;
					[mCircle1 runAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.01 scale:0.9],
										 [CCScaleTo actionWithDuration:0.01 scale:1.0],nil]];
					[mScore1 setString:[NSString stringWithFormat:@"%d",mTouchCount1]];
					[mScoreTotal setString:[NSString stringWithFormat:@"%d",mTouchCount1 + mTouchCount2]];
				}
				else if(touchIn == 1) {
					isTouch = YES;
					if(mTouchState2 == kStateGrabbed) continue;
					mTouchState2 = kStateGrabbed;
					mTouch2 = touch;
					mTouchCount2 ++;
					[mCircle2 runAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.01 scale:0.9],
										 [CCScaleTo actionWithDuration:0.01 scale:1.0],nil]];
					[mScore2 setString:[NSString stringWithFormat:@"%d",mTouchCount2]];
					[mScoreTotal setString:[NSString stringWithFormat:@"%d",mTouchCount1 + mTouchCount2]];
				}
			}
			if(isTouch) 
				[[SimpleAudioEngine sharedEngine] playEffect:@"Tap.wav"];
			break;
		}
		case kStateResult:
			break;
		case kStateFinish:
			break;
	}
}

-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	switch(mGameState) {
		case kStateNone:
			break;
		case kStateBegin: {
			int count = [[touches allObjects] count];
			int i;
			for (i =0; i < count; i++) {
				UITouch* touch = [[touches allObjects] objectAtIndex:i];
				if(touch == mTouch1) {
					mTouchState1 = kStateUngrabbed;
					mTouch1 = nil;
				}
				else if(touch == mTouch2) {
					mTouchState2 = kStateUngrabbed;
					mTouch2 = nil;
				}
			}
			break;
		}
		default:
			break;
	}
}

-(void)drainTime {
	NSTimeInterval timePassed = [self.mStartTime timeIntervalSinceNow];

	if (timePassed < -mTime) {
		timePassed = -mTime;
		[self unschedule:@selector(drainTime)];
		mGameState = kStateResult;
		[mRetry setVisible:YES];
		[mCircle1 setVisible:NO];
		if(mMode == 1)
			[mCircle2 setVisible:NO];
		
		[[SimpleAudioEngine sharedEngine] playEffect:@"Done.wav"];
		[mFinish runAction:[CCSpawn actions:[CCFadeIn actionWithDuration:0.5],
							[CCMoveBy actionWithDuration:0.5 position:ccp(0,-50)],nil]];
		
		OFDelegate nilDelegate;
		NSString* strTmp;
		if(mMode == 0) {
			if(mTime == 10)
				strTmp = @"709436";
			else if(mTime == 20)
				strTmp = @"709466";
			else if(mTime == 30)
				strTmp = @"709476";
			else
				strTmp = @"709486";
		}
		else {
			if(mTime == 10)
				strTmp = @"715347";
			else if(mTime == 20)
				strTmp = @"715357";
			else if(mTime == 30)
				strTmp = @"715367";
			else
				strTmp = @"715377";
		}

		[OFHighScoreService setHighScore:(mTouchCount1 + mTouchCount2)
						  forLeaderboard:strTmp
							   onSuccess:nilDelegate
							   onFailure:nilDelegate];
	}

	float pos = (mTime + timePassed)/mTime;
	[mTimeBar setTextureRect:CGRectMake(0, 0, pos*200, 25)];
	[mTimeBar setColor:ccc3(255-255*pos,255*pos,0)];
	[mTimeValue setString:[NSString stringWithFormat:@"%.02f", mTime + timePassed]];
}

-(void)back {
	[[SimpleAudioEngine sharedEngine] playEffect:@"Menu.wav"];
	[[CCDirector sharedDirector] replaceScene:[LayerSetPos node]];
}

-(void)retry {
	[[SimpleAudioEngine sharedEngine] playEffect:@"Menu.wav"];
	[self reStart];
}

-(int)containsTouchLocation:(UITouch *)touch {
	CGPoint location = [touch locationInView: [touch view]];
	location = [[CCDirector sharedDirector] convertToGL: location];
	if(ccpDistance(mCircle1.position, location) <= kCircleRadius)
		return 0;
	else {
		if(mMode == 1)
			if( ccpDistance(mCircle2.position, location) <= kCircleRadius)
				return 1;
	}			
	return 2;
}

/*
- (void)onEnter {
	if(![TapBurstAppDelegate get].paused) {
		[[CCTouchDispatcher sharedDispatcher] addStandardDelegate:self priority:0];
		[super onEnter];
	}
}

- (void)onExit {
	if(![TapBurstAppDelegate get].paused) {
		[[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
		[super onExit];
	}	
}
*/
- (void) dealloc {
	[mStartTime release];
	[super dealloc];
}
@end
